/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package io.vertx.core.eventbus.impl.clustered;

import io.vertx.core.net.impl.ServerID;
import net.apexes.vertx.ClusteredMessageLogger;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class ConnectionMap extends ConcurrentHashMap<ServerID, ConnectionHolder> {

    private final ClusteredEventBus eventBus;
    private final ClusteredMessageLogger logger;

    public ConnectionMap(ClusteredEventBus eventBus, ClusteredMessageLogger logger) {
        this.eventBus = eventBus;
        this.logger = logger;
    }

    @Override
    public ConnectionHolder get(Object key) {
        ConnectionHolder holder = super.get(key);
        if (holder == null && key instanceof ServerID) {
            ServerID serverID = (ServerID) key;
            holder = new LoggerConnectionHolder(eventBus, serverID, logger);
            ConnectionHolder prevHolder = putIfAbsent(serverID, holder);
            if (prevHolder != null) {
                // Another one sneaked in
                holder = prevHolder;
            } else {
                holder.connect();
            }
        }
        return holder;
    }

}
